<template>
  <view class="min-h-screen bg-white p-4">
    <!-- 表单 -->
    <uv-form ref="formRef" :model="form" :rules="rules">
      <!-- 用户头像 -->
      <view class="mb-6 mt-6 flex justify-center">
        <uv-upload
          :file-list="avatarList"
          :max-count="1"
          @after-read="onAvatarSelect"
        />
      </view>

      <!-- 用户昵称 -->
      <uv-form-item label="昵称" prop="nickname">
        <uv-input
          v-model="form.nickname"
          placeholder="请输入昵称"
          border="surround"
        />
      </uv-form-item>

      <!-- 手机号（只读） -->
      <uv-form-item label="手机号">
        <uv-input
          v-model="form.mobile"
          disabled
          border="surround"
        />
      </uv-form-item>

      <!-- 性别 -->
      <uv-form-item label="性别" prop="gender">
        <uv-radio-group v-model="form.gender" placement="row">
          <view class="mx-2">
            <uv-radio :name="1" label="男" />
          </view>
          <view class="mx-2">
            <uv-radio :name="2" label="女" />
          </view>
        </uv-radio-group>
      </uv-form-item>

      <!-- 个人简介 -->
      <uv-form-item label="简介">
        <uv-textarea
          v-model="form.bio"
          placeholder="介绍一下自己吧"
        />
      </uv-form-item>

      <!-- 保存按钮 -->
      <view class="mt-8 px-4">
        <uv-button type="primary" shape="circle" @click="submitForm">
          {{ $t('save') }}
        </uv-button>
      </view>
    </uv-form>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useUserStore } from '@/store'

definePage({
  style: {
    navigationBarTitleText: '%editUserInfo%',
    navigationBarBackgroundColor: '#FFFFFF',
  },
})

const formRef = ref()
const userStore = useUserStore()
// 表单数据
const form = ref({
  nickname: '',
  mobile: '138****8888',
  gender: 1,
  bio: '',
  avatar: '',
})
const avatarList = ref([])

onLoad(() => {
  const user = userStore.userInfo // 假设 store 有 userInfo
  if (!user)
    return

  form.value.nickname = user.legalUser.nickname || ''
  form.value.mobile = user.legalUser.mobile || ''
  form.value.gender = user.legalUser.sex || 1
  form.value.avatar = user.legalUser.headImage || ''

  if (user.legalUser.headImage) {
    avatarList.value = [{ url: user.legalUser.headImage }]
  }
})

// form 校验规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' as const },
    { min: 2, max: 12, message: '昵称长度 2-12 字', trigger: 'blur' as const },
  ],
  gender: [
    { required: true, type: 'number' as const, message: '请选择性别', trigger: 'change' as const },
  ],
}

// 头像选择
function onAvatarSelect(event) {
  avatarList.value = event.fileList
  form.value.avatar = event.fileList[0]?.url || ''
}

// 保存
function submitForm() {
  formRef.value.validate().then(() => {
    uni.showToast({
      title: '保存成功',
      icon: 'success',
    })
    // TODO: 调接口
  })
}
</script>

<style lang="scss" scoped></style>
